package com.nariano.webapp;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.rmi.server.UID;

import javax.imageio.ImageIO;

import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.FormComponentFeedbackBorder;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.image.resource.DynamicImageResource;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;

import com.nariano.server.domain.engine.Engine;
import com.nariano.server.domain.entities.City;
import com.nariano.server.domain.entities.User;
import com.nariano.server.services.cityservice.CityService;
import com.nariano.server.services.userservice.UserService;
import com.nariano.server.utils.spring.SpringFactory;
import com.octo.captcha.service.image.ImageCaptchaService;

public class AddPlayerConfirmPage extends CreateCityPage {

    private transient UserService userService = SpringFactory.getBean("userService",
            UserService.class);
    private transient CityService cityService = SpringFactory.getBean("cityService",
            CityService.class);

    public AddPlayerConfirmPage(final User user, final City city) {
        
        DynamicImageResource res = new DynamicImageResource() {
            @Override
            protected byte[] getImageData() {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                challengeId = new UID().toString();
                BufferedImage image = SpringFactory.getBean("captchaService",
                        ImageCaptchaService.class).getImageChallengeForID(
                        challengeId, Session.get().getLocale());
                // Writing the image to outputstream
                try {
                    ImageIO.write(image, "png", os);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // flush it in the response
                return os.toByteArray();
            }
          };

        Form form = new Form("form");
        add(form);

        FeedbackPanel feedback = new FeedbackPanel("feedback");
        add(feedback);

        
        final Image image = new Image("captchaImage", res);
        image.setOutputMarkupId(true);
        form.add(image);
        
        form.add(new AjaxFallbackLink("generateCaptcha") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                setResponsePage(new AddPlayerConfirmPage(user, city));  // TODO refresh part of page
            }
          });
        
        form.add(new FormComponentFeedbackBorder("border5").add(new TextField("captchaResponse", new PropertyModel(this,
        "challengeResponse")) {
      @Override
      protected final void onComponentTag(final ComponentTag tag) {
        super.onComponentTag(tag);
        tag.put("value", "");
      }
    }.setRequired(true).add(new AbstractValidator() {

      @Override
      protected void onValidate(IValidatable validatable) {
        if (!SpringFactory.getBean("captchaService", ImageCaptchaService.class)
                .validateResponseForID(challengeId,
            validatable.getValue())) {
          error(validatable);
        }
      }

      @Override
      protected String resourceKey() {
        return "captcha.validation.failed";
      }
      
      
    })));
        
        form.add(new Link("back") {

            @Override
            public void onClick() {
               setResponsePage(EditPlayerPage.class);
            }

        });

        form.add(new Button("submit") {

            @Override
            public void onSubmit() {

                User u = userService.insertUser(user);
                NarianoSession.get().setUser(user);
                createCity(u, city);
                setResponsePage(Index.class);
            }
        });

    }
    
    private String challengeId = null;

    private String challengeResponse;
       

}
